﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;

/**
 * 基于背面消除的模型产生相同但双面的模型
 * 产生的模型，内部面的法线反向，并且三角形绘制顺序是由内到外
 * 这种双面模型主要用于半透明闭合物体采用一个材质时先绘制内部再绘制的正确顺序
 */
public static class GenerateDoubleSidedMeshForSemiTransparency
{

    [MenuItem("Assets/Create/Double-Sided Mesh")]
    static void GenerateDoubleSidedMeshAsset()
    {
        var sourceMesh = Selection.activeObject as Mesh;
        if (sourceMesh == null)
        {
            Debug.LogWarning("You must have a mesh asset selected.");
            return;
        }

        // generate inside mesh
        Mesh insideMesh = Object.Instantiate(sourceMesh);

        // reverse triangles
        int[] triangles = insideMesh.triangles;
        System.Array.Reverse(triangles);
        insideMesh.triangles = triangles;

        // reverse normals
        Vector3[] normals = insideMesh.normals;
        for (int i = 0; i < normals.Length; i++)
            normals[i] = -normals[i];
        insideMesh.normals = normals;

        // combine mesh
        var combinedMesh = new Mesh();
        var combineInstances = new CombineInstance[] {
            new CombineInstance { mesh = insideMesh }, // inside mesh first
            new CombineInstance { mesh = sourceMesh },
        };
        combinedMesh.CombineMeshes(combineInstances, true, false, false);

        Object.DestroyImmediate(insideMesh);

        string path = AssetDatabase.GetAssetPath(sourceMesh);
        if (string.IsNullOrEmpty(path) || !path.StartsWith("Assets"))
        {
            AssetDatabase.CreateAsset(combinedMesh, Path.Combine("Assets", sourceMesh.name + " Double-Sided.asset"));
        }
        else
        {
            AssetDatabase.CreateAsset(combinedMesh, Path.Combine(Path.GetDirectoryName(path), sourceMesh.name + " Double-Sided.asset"));
        }
    }

}
